package com.thinkfit.jy.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.bean.ApplicationBean;
import com.common.lib.bean.SportInfoBean;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.network.OkHttpManager;
import com.thinkfit.jy.R;
import com.thinkfit.jy.adapter.ApplicationAdapter;
import com.thinkfit.jy.adapter.DownloadAdapter;
import com.thinkfit.jy.contract.ApplicationContract;
import com.thinkfit.jy.presenter.ApplicationPresenter;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.DialogCloseApkViewUtils;
import com.thinkfit.jy.utils.DialogViewUtils;
import com.thinkfit.jy.utils.FileUtils;
import com.thinkfit.jy.utils.LogUtils;
import com.thinkfit.jy.utils.RunningAppUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.SystemUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.ToastUtils;
import com.thinkfit.jy.view.ApplicationView;
import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchConfiguration;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetch2core.DownloadBlock;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 娱乐影音
 */
public class ApplicationFragment extends BaseFragment<ApplicationContract.Presenter> implements ApplicationContract.View {

    private ApplicationAdapter mAdapter;
    private ApplicationFragment.BootReceiver mBootReceiver;
    DownloadAdapter downloadAdapter;
    List<DownloadAdapter.DownloadData> downloadDataList = new ArrayList<>();

    ArrayList<String> downloadName = new ArrayList<>();

    public static ApplicationFragment getInstance() {
        Bundle bundle = new Bundle();
//        bundle.putInt(Constants.BUNDLE_EXTRA, index);
//        bundle.putInt(Constants.BUNDLE_EXTRA_2, type);
        ApplicationFragment fragment = new ApplicationFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_application;
    }

    Fetch fetch;
    FetchListener fetchListener = new FetchListener() {

        @Override
        public void onAdded(@NonNull Download download) {
            int position = downloadAdapter.getUrlPosition(download.getUrl());
            DownloadAdapter.DownloadData downloadData = downloadAdapter.getData().get(position);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   position  "+position+"  , packageName : "+downloadData.packageName);
            if(downloadData != null){
                if(download != null){
                    downloadData.downloadId = download.getId();
                    downloadData.download = download;
                    downloadData.downloadPath = FileUtils.getDownloadPath(getContext());
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   downloadData  "+downloadData.toString());
//                    downloadAdapter.addDownload(downloadData);
                    downloadAdapter.notifyItemChanged(position);
                }
            }
        }
        @Override
        public void onQueued(@NonNull Download download, boolean b) {
            if (downloadAdapter != null) {
                int position = downloadAdapter.getPosition(download);
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   onQueued.position  "+position);
                downloadAdapter.setStartAndPausedVisibility(true,position);
                downloadAdapter.setRemovedVisibility(true,position);
                downloadAdapter.setProgressVisibility(true,position);
                downloadAdapter.setDownVisibility(false,position);
                downloadAdapter.update(download, -1, 0);
            }
        }
        @Override
        public void onWaitingNetwork(@NonNull Download download) {

        }
        @Override
        public void onCompleted(@NonNull Download download) {
            File file = new File(download.getFile());
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  tempFile =  "+file.exists());
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  download.getFile =  "+download.getFile());
            List<DownloadAdapter.DownloadData> data = downloadAdapter.getData();
            if(file.exists() && file.isFile()){
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  下载完成");
                int position = downloadAdapter.getPosition(download);
                downloadAdapter.setDownVisibility(false,position);
                downloadAdapter.setStartAndPausedVisibility(false,position);
                downloadAdapter.setRemovedVisibility(true,position);
                downloadAdapter.setProgressVisibility(false,position);
                downloadAdapter.downloadSucceed(true,position);
                downloadAdapter.setInstallProgressVisibility(true,position);
                downloadName.remove(downloadAdapter.getData().get(position).packageName);

                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  data.size : "+data.size());
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  position : "+position);
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  isAvilible : "+isAvilible(getContext(),data.get(position).packageName));
//                if(data.get(position).versionCode > SystemUtils.getVersion(getContext(),data.get(position).packageName)){
//
//                }
//                downloadAdapter.setInstallProgressVisibility(true,position);
                ToastUtils.getInstance().show(getContext(),getContext().getResources().getString(R.string.app_application_installing));
                downloadAdapter.setStateText(getContext().getResources().getString(R.string.app_application_installing),position);

                ((ApplicationPresenter)getPresenter()).install(data.get(position));

            }
        }
        @Override
        public void onError(@NonNull Download download, @NonNull Error error, @Nullable Throwable throwable) {
            throwable.printStackTrace();
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }
        @Override
        public void onDownloadBlockUpdated(@NonNull Download download, @NonNull DownloadBlock downloadBlock, int i) {

        }

        @Override
        public void onStarted(@NonNull Download download, @NonNull List<? extends DownloadBlock> list, int i) {

        }
        @Override
        public void onProgress(@NonNull Download download, long l, long l1) {
            if (downloadAdapter != null) {
                downloadAdapter.setProgressVisibility(true,downloadAdapter.getPosition(download));
                downloadAdapter.update(download, l, l1);
            }
        }
        @Override
        public void onPaused(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

        @Override
        public void onResumed(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

        @Override
        public void onCancelled(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

        @Override
        public void onRemoved(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
                int position = downloadAdapter.getPosition(download);
                downloadAdapter.setStateText("",position);
            }
        }



        @Override
        public void onDeleted(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

    };

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initFetch();
        if(downloadAdapter == null){
            downloadAdapter = new DownloadAdapter(new DownloadAdapter.ActionListener() {
                @Override
                public void onPauseDownload(int id) {
                    fetch.pause(id);
                }

                @Override
                public void onResumeDownload(int id) {
                    fetch.resume(id);
                }

                @Override
                public void onRemoveDownload(int id) {
                    fetch.remove(id);
                }

                @Override
                public void onRetryDownload(int id) {
                    fetch.retry(id);
                }
            });
        }
        downloadAdapter.setOnClick(new DownloadAdapter.Click() {
            @Override
            public void click(View v,DownloadAdapter.DownloadData downloadData,int position) {
                switch (v.getId()){
                    case R.id.ivUninstall:
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    delete "+downloadData.packageName);
                        Intent intent2 = new Intent(Intent.ACTION_DELETE);
                        intent2.setData(Uri.parse("package:" + downloadData.packageName));
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent2);
                        downloadData.isState = false;
                        downloadData.isDelete = true;
                        downloadAdapter.notifyItemChanged(position);
                        break;
                    case R.id.downButton:
                        if(downloadName.size() >= 3){
                            ToastUtils.getInstance().show(getContext(),getString(R.string.app_application_again_later));
                            return;
                        }
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    startDownload "+downloadData.packageName);
                        downloadData.isState = true;
                        startDownload(downloadData,position);
                        break;
                    case R.id.ivIcon:
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    open : "+downloadData.packageName);
                        RunningAppUtils.getInstance().init(getContext());
                        ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
                        boolean isOpen = RunningAppUtils.getInstance().isOpen(downloadData.packageName);
                        LogUtils.getInstance().l(LogUtils.HINT,"aaaaaaaaaaaaaaaaaaaaaaaaa   isOpen : "+isOpen);
                        LogUtils.getInstance().l(LogUtils.HINT,"aaaaaaaaaaaaaaaaaaaaaaaaa   currentRunningApp.size() : "+currentRunningApp.size());
                        if(currentRunningApp.size()>=3 && !isOpen){
                            DialogCloseApkViewUtils.getInstance().initView(getContext(),downloadData.packageName);
                        }else {
                            intent2 = getContext().getPackageManager().getLaunchIntentForPackage(downloadData.packageName);
//                        intent2.setData(Uri.parse("package:" + downloadData.packageName));
//                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent2);
                        }
                        break;

                }

            }
        });

        downloadAdapter.setOnLongClick(new DownloadAdapter.ClickLong() {
            @Override
            public void clickLong(View v, DownloadAdapter.DownloadData downloadData, int position) {
                switch (v.getId()){
                    case R.id.ivIcon:
                        DialogViewUtils.getInstance().setClosePackageName(downloadData.packageName);
                        DialogViewUtils.getInstance().initView(getAppContext(),false,DialogViewUtils.EXIT_APP);
                        break;
                }
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addDataScheme("package");
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        mBootReceiver = new BootReceiver();
        getContext().registerReceiver(mBootReceiver, filter);
//        if (DataManager.Companion.getInstance().getMainStyle() == 3) {
//            setBackground(R.id.rl, R.drawable.app_bg_xm);
//        }

        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 5);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(gridLayoutManager);

//        ApplicationView.getInstance().initView(getContext().getApplicationContext(),false);
        recyclerView.setAdapter(downloadAdapter);
    }


    public void  initFetch(){
        if (fetch == null) {
            FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(getContext())
//                    .enableRetryOnNetworkGain(true)
                    .setDownloadConcurrentLimit(2)
//                    .setHttpDownloader(new OkHttpDownloader(Downloader.FileDownloaderType.PARALLEL))
//                    .enableAutoStart(false)
//                    .setHttpDownloader(new HttpUrlConnectionDownloader(Downloader.FileDownloaderType.PARALLEL))
                    .build();

            fetch = Fetch.Impl.getInstance(fetchConfiguration);

            fetch.addListener(fetchListener);
        }


    }

    public void startDownload(DownloadAdapter.DownloadData downloadData,int position){
        String file = FileUtils.getDownloadPath(getContext())+ downloadData.downloadFileName;
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  click.position  : "+position);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  file  : "+file);
        downloadName.add(downloadData.packageName);
//                downloadAdapter.setStateText("准备下载中",position);
        File file1 = new File(file);
        if(file1.exists() && file1.isFile()){
            file1.delete();
        }

        String url = downloadData.url;
        Request request = new Request(url, file);
        fetch.enqueue(request, request1 -> {
            //Request enqueued for download
        }, error -> {
            //Error while enqueuing download
        });
    }


    @NonNull
    @Override
    protected ApplicationContract.Presenter onCreatePresenter() {
        return new ApplicationPresenter(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        SportsStatusBarViewUtils.getInstance().isMain(false);
        getPresenter().getApkList();//获取应用列表
//        setBackground(R.id.rl, ThemeUtils.getInstance().getMainTheme());
    }

    @Override
    public void onStop() {
        super.onStop();
        DeviceTypeUtils.showBackButton(getContext().getApplicationContext());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    public void onDestroy() {
        super.onDestroy();
//        if(mFloatingView != null){
//            mFloatingView.hide();
//        }
        if(fetch != null){
            fetch.removeAll();
            fetch.cancelAll();
            fetch.removeListener(fetchListener);
//            fetch.close();
            fetch = null;
        }
        downloadName.clear();
        getContext().unregisterReceiver(mBootReceiver);
    }

    private ApplicationAdapter getAdapter() {
        if (mAdapter == null) {
            mAdapter = new ApplicationAdapter(getContext(),ApplicationAdapter.APPLICATION);

            mAdapter.addChildClickViewIds(R.id.ivUninstall);
            mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    switch (view.getId()) {
                        case R.id.ivUninstall:
                            Intent intent2 = new Intent(Intent.ACTION_DELETE);
                            intent2.setData(Uri.parse("package:" + mAdapter.getItem(position).getAppid()));
                            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent2);
                            break;
                    }
                }
            });
            mAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    ApplicationBean bean = getAdapter().getItem(position);
//                    mFloatingView.setImageUrl(bean.getIcon());
//                    mFloatingView.show();

                    if (bean.getInstallStatus() == 1) {
                        bean.setInstallStatus(0);
                    }
                    if (bean.getInstallStatus() != 2) {
                        switch (bean.getDownloadStatus()) {
                            case 0:
                            case 3:
                                bean.setProgress(0);
                                bean.setDownloadStatus(1);
                                getAdapter().notifyDataSetChanged();
                                OkHttpManager.Companion.getInstance().downloadApplication(bean);
                                break;
                            case 2:
                                if (bean.getDownloadFile() != null && bean.getDownloadFile().exists()) {
                                    bean.setInstallStatus(1);
                                    SystemUtils.getInstance().installApk(getContext(),bean.getDownloadFile());
                                } else {
                                    bean.setProgress(0);
                                    bean.setDownloadStatus(1);
                                    getAdapter().notifyDataSetChanged();
                                    OkHttpManager.Companion.getInstance().downloadApplication(bean);
                                }
                                break;
                        }
                    } else {
                        RunningAppUtils.getInstance().init(getContext());
                        ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
                        boolean isOpen = RunningAppUtils.getInstance().isOpen(bean.getAppid());
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   isOpen : "+isOpen);
                        if(!isOpen){//是否已经打开
                            if(currentRunningApp.size()>=3){
                                DialogCloseApkViewUtils.getInstance().initView(getContext(),bean.getAppid());
                            }else {
                                PackageManager packageManager = getContext().getPackageManager();
                                Intent intent = packageManager.getLaunchIntentForPackage(bean.getAppid());
                                if (intent != null) {
                                    startActivity(intent);
                                }
                            }
                        }else {
                            PackageManager packageManager = getContext().getPackageManager();
                            Intent intent = packageManager.getLaunchIntentForPackage(bean.getAppid());
                            if (intent != null) {
                                startActivity(intent);
                            }
                        }
                    }
                }
            });
        }
        return mAdapter;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    public void getApkListSuccess(ArrayList<ApplicationBean> list) {
        downloadAdapter.removeAllDownload();
        Observable.create(new ObservableOnSubscribe<List<DownloadAdapter.DownloadData>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<DownloadAdapter.DownloadData>> emitter) throws Throwable {

                ArrayList<ApplicationBean> list1 = OkHttpManager.Companion.getInstance().getMDownLoadingApplication();
                if (!list1.isEmpty()) {
                    for (ApplicationBean bean1 : list1) {
                        for (int i = 0; i < list.size(); ) {
                            if (bean1.getAppid().equals(list.get(i).getAppid())) {  //如果检测到有正在下载的apk，则需要替换一下，方便更新下载UI
                                list.remove(i);
                                list.add(i, bean1);
                                break;
                            }
                            ++i;
                        }
                    }
                }
                PackageManager packageManager = getContext().getPackageManager();
                // 获取已安装的app信息
                List<PackageInfo> pkgInfos = packageManager.getInstalledPackages(0);
                ArrayList<ApplicationBean> list2 = new ArrayList<>();
                int i = -1 ;
                if (pkgInfos != null) {
                    for (ApplicationBean bean : list) {
                        for (PackageInfo info : pkgInfos) {
                            //  Log.e("aaaaaaaaaa", info.packageName+", "+info.applicationInfo.loadLabel(packageManager).toString());
                            if (bean.getAppid().equals(info.packageName)) {
                                bean.setInstallStatus(2);
                                i++;
                                break;
                            }
                        }
                        if(bean.getInstallStatus() == 2){
                            list2.add(i,bean);
                        }else {
                            list2.add(bean);
                        }


                    }
                }
                for (ApplicationBean applicationBean : list2){
                    DownloadAdapter.DownloadData downloadData = new DownloadAdapter.DownloadData();
                    downloadData.name = applicationBean.getAppname();
                    downloadData.packageName = applicationBean.getAppid();
                    downloadData.url = applicationBean.getDownload();
                    downloadData.icon = applicationBean.getIcon();
                    downloadData.downloadFileName = applicationBean.getAppid()+".apk";
                    downloadData.downloadPath = FileUtils.getDownloadPath(getContext());
                    downloadAdapter.addDownload(downloadData);
                    downloadDataList.add(downloadData);
                }
                emitter.onNext(downloadDataList);
            }
        }).subscribe(new Observer<List<DownloadAdapter.DownloadData>>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull List<DownloadAdapter.DownloadData> o) {

            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

//        ApplicationView.getInstance().setAppAdapterData(downloadDataList);
//        ApplicationView.getInstance().visibleLayout();

//        getAdapter().setNewInstance(list);
    }

    @Override
    public void getSportInfoSuccess(SportInfoBean bean) {

    }

    @Override
    public DownloadAdapter getDownloadAdapter() {
        return downloadAdapter;
    }

    @Override
    public void installOver(String packageName) {
        int position = downloadAdapter.getPackagePosition(packageName);
        ToastUtils.getInstance().show(getContext(),getString(R.string.app_application_installation_completed));
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   安装完成 ");
        downloadAdapter.setStateText("",position);
    }

    @Override
    public void refreshVersion(String packageName) {
        int packagePosition = downloadAdapter.getPackagePosition(packageName);
        downloadAdapter.setProgressVisibility(false,packagePosition);
        downloadAdapter.setDownVisibility(true,packagePosition);
        downloadAdapter.setRemovedVisibility(false,packagePosition);
        downloadAdapter.setRemovedVisibility(false,packagePosition);
        downloadAdapter.setInstallProgressVisibility(false,packagePosition);
    }

    @Override
    public Context getAppContext() {
        return getContext();
    }

    public boolean isAvilible(Context context, String packageName) {
        //1.PackageManager 包的管理者对象
        PackageManager pm = context.getPackageManager();
        //2.获取应用的配置信息,在此处传递0获取的是基本信息(包名,版本名称,版本号)
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            if(packageName.equals(packageInfo.packageName)){
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;

    }

    class BootReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //接收安装广播
            if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) ||
                    intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
                String packageName = intent.getDataString();
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  action: " + intent.getAction() + ", " + packageName);
                downloadAdapter.installSuccess(packageName);
                int packagePosition = downloadAdapter.getPackagePosition(packageName);
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  action: " + intent.getAction() + ", " + packagePosition);
                downloadAdapter.setInstallProgressVisibility(false,packagePosition);
                ((ApplicationPresenter) getPresenter()).setIsInstall(false);
                ((ApplicationPresenter) getPresenter()).installOver(packageName);
                installOver(packageName);
                downloadAdapter.notifyDataSetChanged();
//                getAdapter().installSuccess(packageName);
            } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) { //接收卸载广播
//                String packageName = intent.getDataString();
                String packageName = intent.getDataString();
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  action: " + intent.getAction() + ", " + packageName);
                downloadAdapter.notifyDataSetChanged();
//                getAdapter().unInstallSuccess(packageName);
            }
        }
    }

}
